/*
https://leetcode-cn.com/problems/shortest-unsorted-continuous-subarray/solution/zui-duan-wu-xu-lian-xu-zi-shu-zu-by-leet-yhlf/
 */
public class Solution581 {
    public int findUnsortedSubarray(int[] nums) {
        int n=nums.length;
        int max=Integer.MIN_VALUE,right=-1;
        int min=Integer.MAX_VALUE,left=-1;
        for (int i=0;i<n;i++){
            if (nums[i]>=max){
                max=nums[i];
            }else {
                right=i;
            }
        }
        for (int i=n-1;i>=0;i--){
            if (nums[i]<=min){
                min=nums[i];
            }else{
                left=i;
            }
        }
       return right==-1?0:right-left+1;
    }

    public static void main(String[] args) {
        System.out.println(new Solution581().findUnsortedSubarray(new int[]{1,2,3,3,3}));
    }
}
